package com.zlp.mall.common.api;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.List;

/**
 * 分页数据封装类
 * @author ZouLiPing
 */
@Data
public class Pager<T> {

    @ApiModelProperty(value = "当前页数")
    private Integer pageNum;

    @ApiModelProperty(value = "每页记录数")
    private Integer pageSize;

    @ApiModelProperty(value = "总页数")
    private Integer totalPage;

    @ApiModelProperty(value = "总记录数")
    private Long total;

    @ApiModelProperty(value = "列表数据")
    private List<T> list;

    public Pager(){

    }

    /**
     * 将 MyBatis Plus 分页结果转化为通用结果
     */
    public static <T> Pager<T> restPage(Page<T> pageResult) {

        Pager<T> result = new Pager<>();
        // 当前页
        result.setPageNum(Convert.toInt(pageResult.getCurrent()));
        // 一页多少条数据
        result.setPageSize(Convert.toInt(pageResult.getSize()));
        // 总数据数量
        result.setTotal(pageResult.getTotal());
        // 总页数
        result.setTotalPage(Convert.toInt(pageResult.getTotal()/pageResult.getSize()+1));
        // 当前页数据
        result.setList(pageResult.getRecords());
        return result;
    }

    /**
     * 将SpringData分页后的list转为分页信息
     */
    public static <T> Pager<T> restPage(org.springframework.data.domain.Page<T> pageInfo) {

        Pager<T> result = new Pager<>();
        result.setTotalPage(pageInfo.getTotalPages());
        result.setPageNum(pageInfo.getNumber());
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotalElements());
        result.setList(pageInfo.getContent());
        return result;
    }

    /**
     * 分页
     * @param list        列表数据
     * @param totalCount  总记录数
     * @param pageSize    每页记录数
     * @param currPage    当前页数
     */
    public Pager(List<T> list, Long totalCount, int pageSize, int currPage) {
        this.list = list;
        this.total = totalCount;
        this.pageSize = pageSize;
        this.pageNum = currPage;
        this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
    }

}
